
'use strict';

const BaseService = require("./base");


class TopicService extends BaseService{
   // 获取话题列表
   async topicList(body){
        // 筛选项：根据名称模糊查询
        const params = this.app._.cloneDeep(body);
        if(params.all){
            const rows = await this.app.model.Topic.findAll({
                attributes:{exclude:['delete_time']},
            })
            return rows
        }else{
            const {count,rows} = await this.app.model.Topic.findAndCountAll({
                distinct:true,
                where:this.queryWhere(params),
                attributes:{exclude:['delete_time']}, 
                ...this.orderOption(params.order),
                ...this.pageParam(params)
            });
            return this.paginate(count, rows,params);
        }   
        
    }

    // 排序
    orderOption(orderType){
        const option = {
            'hotAsc':['hoy_count','ASC'],
            'hotDesc':['hoy_count','DESC'],
        }
        if(orderType){
            return {order:[option[orderType]]}
        }else{
            return {}
        }
    }

    // 筛选项
    queryWhere(params){
        const {Op} = this.app.Sequelize
        const {searchWord} = params
        const where = {}
        if(searchWord!==''){
            where[Op.and] = {'topic_name':{[Op.like]:`%${searchWord}%`}}
        }
        return where
    }

    // 创建话题
    async createTopic(body){
        const params = this.app._.cloneDeep(body)
        params.create_time = new Date()
        await this.app.model.Topic.create(params)
    }
    //删除话题 (批量)
    async deleteTopic(ids){
        const { Op } = this.app.Sequelize;
        await this.app.model.Topic.destroy({
          where:{
            id:{
              [Op.in]:ids
            }
          }
        })
    }

    //编辑话题
    async updateTopic(body){
        console.log(body);
        const {id,topic_name,topic_describe} = body
        await this.app.model.Topic.update({ topic_name,topic_describe,update_time:new Date() },{
            where:{
                id:id
            }
        })
    }
}


module.exports = TopicService;